var api = require('../../utils/api.js');

Page({
  data: {
    recordId: '',
    record: {},
    dateTimeStr: ''
  },

  onLoad: function(options) {
    var id = options.id;
    this.setData({ recordId: id });
    this.loadRecordDetail();
  },

  loadRecordDetail: function() {
    var that = this;
    api.getEmotionRecordDetail(this.data.recordId).then(function(res) {
      if (res.code === 200 && res.data) {
        var record = res.data;
        // 处理头像
        record.avatar = that.getEmotionAvatar(record.emotion);

        // 处理 ai_response 字段
        if (typeof record.ai_response === 'string') {
          try {
            var obj = JSON.parse(record.ai_response);
            if (obj && (obj.automatic_thoughts || obj.new_perspective || obj.affirmation)) {
              record.ai_response = obj;
            }
          } catch (e) {}
        }
        that.setData({ 
          record: record,
          dateTimeStr: that.formatDateTime(record.created_at)
        });
      }
    });
  },

  getEmotionAvatar: function(emotion) {
    if (emotion === '兴奋' || emotion === '满足' || emotion === '开心' || emotion === '高兴') {
      return '/assets/happy.png';
    }
    if (emotion === '自信' || emotion === '平静' || emotion === '愉悦') {
      return '/assets/confident.png';
    }
    if (emotion === '焦虑' || emotion === '悲伤' || emotion === '内疚') {
      return '/assets/sad.png';
    }
    if (emotion === '共情') {
      return '/assets/professional.png';
    }
    if (emotion === '愤怒' || emotion === '恐惧' || emotion === '失望') {
      return '/assets/angry.png';
    }
    return '/assets/professional.png';
  },

  formatDateTime: function(dateStr) {
    if (!dateStr) return '';
    var d = new Date(dateStr);
    var month = d.getMonth() + 1;
    var day = d.getDate();
    var hour = d.getHours().toString().padStart(2, '0');
    var min = d.getMinutes().toString().padStart(2, '0');
    return month + '月' + day + '日 ' + hour + ':' + min;
  },

  onViewAll: function() {
    wx.navigateBack();
  }
});